PostgreSQL 全文搜索 搜索结果高亮
1 背景知识
PostgreSQL 可以使用 ts_headline
函数显示匹配搜索的文档片段,并且高亮显示。
2 语法大纲
ts_headline([ config regconfig, ] document text, query tsquery [, options text ]) returns text
参数 | 说明 |
---|---|
config regconfig | 指定解析器。 |
document text | 指定一个文档 。 |
query tsquery | 指定一个 查询 。 |
returns text | 返回一个包含 查询 的文档片段。并高亮 查询 。 |
2.1 options
ts_headline
函数提供 option=value
选项表达式。value
参数如下所示:
MaxWords,MinWords
:
此参数为整数类型,决定输出的上下文的长度。默认为35
,15
。ShortWord
:
此参数为整数类型,决定输出的上下文中,删除短于此数值的单词。默认为3
。HighlightAll
此参数为布尔类型,决定输出的上下文是否全部高亮。默认为false
。MaxFragments
:
此参数为整数类型,决定输出的上下文的最大段落数。默认为0
。StartSel
,StopSel
(strings):
此参数为字符串类型,用于区分查询
词位 的界限,默认为<b>
和</b>
,适合于HTML
文档输出。FragmentDelimiter
(string):
此参数为字符串类型,当显示多个上下文关系时,使用的文档分隔符。默认为...
。
3 高亮查询
<b>query</b>
为 HTML 高亮显示语法。
SELECT ts_headline('english',
'The most common type of search
is to find all documents containing given query terms
and return them in order of their similarity to the
query.',
to_tsquery('english', 'query & similarity'));
ts_headline
------------------------------------------------------------
containing given <b>query</b> terms +
and return them in order of their <b>similarity</b> to the+
<b>query</b>.
(1 row)
4 带有高亮控制的查询
**search**
为 MarkDown 高亮语法。
SELECT ts_headline('english',
'Search terms may occur
many times in a document,
requiring ranking of the search matches to decide which
occurrences to display in the result.',
to_tsquery('english', 'search & term'),
'MaxFragments=10, MaxWords=7, MinWords=3, StartSel=**, StopSel=**');
ts_headline
------------------------------------------------------------
**Search** **terms** may occur +
many times ... ranking of the **search** matches to decide
(1 row)